import { onMounted, ref, unref } from "vue";
import { getDictByNames } from "@/api/system/dict";
import type { GetDictModel } from "@/api/system/model/dictModel";
import { Recordable } from "/#/global";

export function useDict(dictNames: Array<string>) {
  console.log("字典使用");

  const dicts = ref<Array<GetDictModel>>([]);

  const getDicts = async () => {
    const res = await getDictByNames(dictNames);
    dicts.value = res;
    return getOptions();
  };

  const getOptions = (): Recordable => {
    const dictOption = unref(dicts);
    let option: Recordable = {};
    dictOption.map((item) => {
      option[item.name] = item.dictDetails;
      return option;
    });
    return option;
  };

  return {
    getDicts,
    dicts,
  };
}

/**
 * 选项来源，数据字典，表中分组字段
 * @param api api请求
 * @param setOptions   设置选项
 * @param dictNames  字典名称
 * @returns
 */
export function useOptions(
  setOptions: Function,
  api: (...arg: any) => Promise<any> = getDictByNames,
  dictNames?: Array<string>
) {
  console.log("字典选项使用");

  const dicts = ref<Array<GetDictModel>>([]);
  const options = ref<Recordable>();

  const getDicts = async () => {
    const res = api && (await api(dictNames));

    dicts.value = res;
    if (dictNames) {
      options.value = getOptions();
      setOptions(options);
    } else {
      setOptions(dicts);
    }
  };

  onMounted(getDicts); // 在 `mounted` 时调用 `getDicts`

  const getOptions = (): Recordable => {
    const dictOption = unref(dicts);
    let option: Recordable = {};
    dictOption.map((item) => {
      option[item.name] = item.dictDetails;
      return option;
    });
    return option;
  };

  return {
    getDicts,
    dicts,
    options,
  };
}
